import _ from 'lodash'
import fetch from 'cross-fetch'

export class ApiServerClient {
  constructor(url, options) {
    this.url = url
    this.options = options || {}
  }

  async request(url, opts) {
    const response = await fetch(_.join([this.url, url], '/'), _.merge({}, this.options, opts))
    const body = await getResponseBody(response);
    if (!response.ok) {
      throw typeof body === 'string' ? new StatusError(body) : new StatusError(body.message, body.reason)
    }
    return body
  }
}

function getResponseBody(response) {
  const contentType = response.headers.get('Content-Type')
  if (contentType && contentType.startsWith('application/json')) {
    return response.json()
  } else {
    return response.text()
  }
}

export class StatusError extends Error {
  constructor(message, reason) {
    super(message)
    this.reason = reason
  }
}
